package com.banmoon.utils;

import cn.hutool.core.util.StrUtil;

import java.util.concurrent.*;

public class CyclicBarrierTest {

    public static void main(String[] args) {
        CyclicBarrier cyclicBarrier = new CyclicBarrier(3, () -> {
            System.out.println("======= 当前阶段已完成 =======");
        });
        new Thread(new Demo(cyclicBarrier), "线程A").start();
        new Thread(new Demo(cyclicBarrier), "线程B").start();
        new Thread(new Demo(cyclicBarrier), "线程C").start();
    }


}

class Demo implements Runnable{

    private CyclicBarrier cyclicBarrier;

    public Demo(CyclicBarrier cyclicBarrier) {
        this.cyclicBarrier = cyclicBarrier;
    }

    @Override
    public void run() {
        try {
            String threadName = Thread.currentThread().getName();
            System.out.println(StrUtil.format("{}：准备就绪", threadName));
            TimeUnit.SECONDS.sleep(3);
            // 等待所有线程都就绪
            cyclicBarrier.await();

            System.out.println(StrUtil.format("{}：上台发言", threadName));
            TimeUnit.SECONDS.sleep(3);
            // 等待所有线程都上台发言
            cyclicBarrier.await();

            System.out.println(StrUtil.format("{}：散会回家", threadName));
            TimeUnit.SECONDS.sleep(1);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
